package com.yangwp.jie.controller;

import com.yangwp.jie.common.enums.RetCodeEnum;
import com.yangwp.jie.common.utils.MapUtils;
import com.yangwp.jie.model.JieUser;
import com.yangwp.jie.service.JieUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RequestMapping("/jie/login")
public class LoginController {

    @Autowired
    private JieUserService jieUserService;

    @RequestMapping("")
    public String login(){
        return "/main/login.ftl";
    }


    @RequestMapping("/check")
    @ResponseBody
    public Map<String, Object> check(@RequestBody JieUser user, HttpServletResponse response){

        if(StringUtils.isBlank(user.getNickName()) || StringUtils.isBlank(user.getPassword())){
            return MapUtils.getRetMap(RetCodeEnum.MISSING_PARAM);
        }

        if(!jieUserService.loginCheck(user.getNickName(), user.getPassword())){
            return MapUtils.getRetMap(RetCodeEnum.PARAM_ERROR);
        }

        Cookie cookie = new Cookie("jie_name", user.getNickName());
        cookie.setMaxAge(365*24*3600);
        cookie.setPath("/");
        response.addCookie(cookie);

        return MapUtils.getRetMap(RetCodeEnum.SUCCESS);
    }
}
